package cn.miaoyao.miaoyaoms.controller;
import cn.miaoyao.miaoyaoms.entity.Limits;
import cn.miaoyao.miaoyaoms.entity.User;
import cn.miaoyao.miaoyaoms.service.LimitsService;
import cn.miaoyao.miaoyaoms.service.UserService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jdk.xml.internal.XMLSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sun
 * @since 2023-03-28
 */
@RestController
public class LimitsController {
    @Autowired
    private LimitsService limitsService;
    @Autowired
    private UserService userService;

    /**
     * 获取所有用户的权限信息展示
     * @return
     */
    @GetMapping("userLimits")
    public String getlimits(@RequestParam(value = "page",defaultValue = "1") String page,
                            @RequestParam(value = "limits",defaultValue = "10")String limits,
                            @RequestParam(value = "phone",defaultValue = "") String phone,
                            @RequestParam(value = "email",defaultValue = "") String email,
                            HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        Page<Limits> limitsPage = new Page<Limits>(Long.valueOf(page), Long.valueOf(limits));
        LambdaQueryWrapper<User> ulw = new LambdaQueryWrapper<>();
        ulw.eq(User::getPhone,phone.trim()).eq(User::getEmail,email.trim());
        User user = userService.getOne(ulw);
        map.put("code",0);
        map.put("msg","操作成功");
        if(user==null){
            //当没有进行搜索功能的时候
              limitsService.page(limitsPage, null);
        }else{
            //当进行搜索功能的时候
            LambdaQueryWrapper<Limits> lsw = new LambdaQueryWrapper<>();
            limitsService.page(limitsPage, lsw.eq(Limits::getUid, user.getUid()));
        }
        map.put("count",limitsPage.getTotal());
        map.put("data",limitsPage.getRecords());
        return JSON.toJSONString(map);
    }

    /**
     * 权限修改
     * @return
     */
    @PostMapping("updatePermission")
    public Boolean updatePermission(Limits limits){
        return limitsService.updateById(limits);//返回是否修改成功。
    }

    /**
     * 权限回显
     * @param id
     * @return
     */
    @GetMapping("permissionShow/{id}")
    public String permissionShow(@PathVariable Integer id){
        return JSON.toJSONString(limitsService.getById(id));
    }
}

